/**
 * @Auther taiping
 * @最后修改日期 2022-04-27
 * 重写错误和警告信息
 */
import type { App } from 'vue';
import { witLog } from './logColor'
import { nextTick } from "vue";
import { useErrorLog } from '@/store/pinia/modules/errorLog'

//源错误信息
interface SourceError {
    subject?: string,
    code?: number,
    message?: string,
    cause?: SourceError | AggregateError
}

//聚合源错误信息
interface AggregateError extends SourceError {
    errors: Array<SourceError|AggregateError>
}

//uni错误信息
interface UniError {
    errSubject: string,
    errCode: number,
    errMsg: string,
    data?: Object,
    cause?: SourceError | AggregateError
}

//回调函数
const CallBack = (err:UniError) => {
    console.log(JSON.stringify(err));
}

const errorStore = useErrorLog();
const {setErrorLogInfo} = errorStore;
/**
 *
 * @param app vue app实例
 */
export function errLog(app: App<Element>){
    app.config.errorHandler = (err: any, vm: any, info: any) => {
        let errRouter = 'App.vue'
        if(getCurrentPages().length) {
            // @ts-ignore
            errRouter = getCurrentPages()[0].route
        }
        witLog.witLog('Wit-UI', 'ErrorHandler', 'error')
        witLog.witError(err, errRouter, info, 'error')
        nextTick(() => {
            // store.dispatch('errorLog/setErrorLog', { err, vm, info, errRouter })
            setErrorLogInfo({ err, vm, info }).then();
        }).then()
    }
    app.config.warnHandler = (msg: any, vm: any, trace: any) => {
        let str = trace.substring(12).substring(0, trace.lastIndexOf("<"))
        str = str.substring(0, str.lastIndexOf("\n"))
        const errRouter = getCurrentPages()[0].route
        witLog.witLog('Wit-UI', 'WarningHandler', 'warning')
        witLog.witError(msg, errRouter, trace, 'warning')
    }
    window.onerror = (err, url, line, column, errObj) => {
        witLog.colorErr(err)
        witLog.colorErr(url)
        witLog.colorErr(line)
        witLog.colorErr(column)
        witLog.colorErr(errObj)
    }
}
